const User = require('../models/User');
const { redisClient } = require('../config/redis');

exports.getProfile = async (ctx) => {
  try {
    const userId = ctx.state.user.id;
    
    // Try to get profile from cache
    const cachedProfile = await redisClient.get(`profile:${userId}`);
    
    if (cachedProfile) {
      ctx.body = JSON.parse(cachedProfile);
      return;
    }
    
    const user = await User.findById(userId).select('-password');
    
    // Cache profile for 1 hour
    await redisClient.setEx(`profile:${userId}`, 3600, JSON.stringify(user));
    
    ctx.body = user;
  } catch (err) {
    ctx.status = 400;
    ctx.body = { error: err.message };
  }
};

exports.updateProfile = async (ctx) => {
  try {
    const userId = ctx.state.user.id;
    const updates = ctx.request.body;
    
    // Remove sensitive fields from updates
    delete updates.password;
    
    const user = await User.findByIdAndUpdate(
      userId,
      updates,
      { new: true, runValidators: true }
    ).select('-password');
    
    // Update cache
    await redisClient.setEx(`profile:${userId}`, 3600, JSON.stringify(user));
    
    ctx.body = user;
  } catch (err) {
    ctx.status = 400;
    ctx.body = { error: err.message };
  }
};